#!/bin/bash

cd /code
source main-var.sh
export buildAt="$(date '+%Y-%m-%d %H:%M:%S')"

#function print-report(){
#  echo "﹍﹎﹍﹎﹍﹎﹎﹎"
#  echo "产品线: $productLine_name ($productLine_code)"
#  echo "开发语言: $language:$languageVersion"
#  echo "K8s服务名: $serviceName"
#  echo "git分支: $gitBranch"
#  echo "构建文件夹: $folder"
#  echo "注册中心: $msDeployEnvEnum"
#  echo "注册中文名: 中台api"
#  echo "注册名: $appCnName"
#  echo "运行环境: $msDeployEnvEnum - $profile"
#  echo "集群名: $clusterCode"
#  echo "docker镜像: $serviceName:$dockerImageVersion"
#  echo "git仓库: $gitUrl"
#  echo "git提交id: $gitCommitId"
#  echo "git提交时间: $gitCommitAt"
#  echo "生成时间: $buildAt"
#  echo "﹊﹉﹊﹉﹊﹉﹊﹊"
#}


function show-file(){
    r=$?
    file_name="$1"
    line="$2"
    line_tail="$3"
    if [ "$file_name" == "" ]; then
        echo "没有 file_name 参数"
        return $r || 1
    fi

    if [ ! -f $file_name ]; then
        echo "找不到文件 $file_name"
        return $r || 1
    fi

    if [[ $debug == true ]]; then
        cat $file_name;
        return $r
    fi

    if [ "$line_tail" == "" ]; then
        line_tail=$line
    fi

    total=`cat $file_name | wc -l`
    show_total=$(( $line + $line_tail ))
    if [ $show_total -ge $total ]; then
        cat $file_name
    else
        echo "前$line行日志:"
        head -n $line $file_name
        echo "〘…后$line_tail行日志:…〙"
        tail -n $line_tail $file_name
    fi
    return $r
}



function pre_build(){

    if [ -f $folder/pre_build.sh ]; then
        echo "重要消息!编译前钩子: $folder/pre_build.sh"
        source $folder/pre_build.sh
    fi


    if [ -f ./pre_build.sh ]; then
        echo "重要消息!编译前钩子: pre_build.sh"
        source ./pre_build.sh
    fi


    if [ -f ./sys-pre-build.sh ]; then
        echo "重要消息!编译前钩子: sys-pre-build.sh"
        source ./sys-pre-build.sh
    fi
}


function java_build(){

    if [ "$folder" != "." ]; then
      pl=" -am -pl $folder"
    fi

    echo "﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹍﹎﹍﹎﹍﹎﹍﹎﹎﹍﹎﹎﹍﹎﹎﹎"
    if [ "$isLib" == "true" ]; then
        echo "mvn clean deploy  -Dmaven.test.skip=true -e -U -P public $pl"
        echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"
        mvn clean deploy -Dmaven.test.skip=true -e -U  -P public $pl

        if [ $? -ne 0 ]; then
          echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "部署失败!!!" ;
          return 1;
        fi

        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "部署成功."
    else
      echo "mvn clean package  -Dmaven.test.skip=true -e -U -P public,$msDeployEnvEnum $pl"
      echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"
      mvn clean package -Dmaven.test.skip=true -e -U -P public,$msDeployEnvEnum $pl

      if [ $? -ne 0 ]; then
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "打包失败!!!" ;
        return 1;
      fi

      echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "打包成功."

      if [ -d $folder/res-runtime ]; then
        cp -rf $folder/res-runtime/.  $folder/
      fi

      echo "移除 target 临时文件夹"

      cd $folder/target
        ls -1d */  | grep -v lib | while read line; do
             dir="${line%*/}";
             rm -rf $dir
        done
      cd -

      mkdir -p $folder/target/lib
    fi
}


function install_package(){
    if [ "$env_removeNpmLock" = "true" ]; then
      rm -rf package-lock.json yarn.lock
    fi

    echo "﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹍﹎﹍﹎﹍﹎﹍﹎﹎﹍﹎﹎﹍﹎﹎﹎"
    if [ "${env_packageTool}" == "npm" ]; then
       echo -e `date "+%Y-%m-%d %H:%M:%S"` "npm install --registry=${env_nexusServerUrl}/repository/npm-group --no-package-lock"
       echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"
       npm install --registry=${env_nexusServerUrl}/repository/npm-group --no-package-lock
    elif [ "${env_packageTool}" == "yarn" ]; then
       echo -e `date "+%Y-%m-%d %H:%M:%S"` "yarn install --registry ${env_nexusServerUrl}/repository/npm-group --no-lockfile"
       echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"
       yarn install --registry ${env_nexusServerUrl}/repository/npm-group --no-lockfile
    else
      echo "不识别的前端打包工具 ${env_packageTool} !"
      return 1;
    fi

    if [ $? -ne 0 ]; then
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` '安装依赖失败!!!'
        return 1
    else
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` '安装依赖成功!'
    fi
}

function node_build(){
    cd $folder
      pwd

      install_package

      if [ -f  .npmrc ]; then
        echo "存在 .npmrc , 内容:"
        cat .npmrc
        echo ""
      fi
      echo "﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹎﹎﹎"
      if [ "$isLib" == "true" ]; then
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "${env_packageTool} publish "
        echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"
        ${env_packageTool} publish

        if [ $? -ne 0 ]; then
          echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "部署失败!!!" ;
          return 1;
        fi

        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "部署成功."
      else
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "${env_packageTool} run "${buildScript}
        echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"
        ${env_packageTool} run ${buildScript}

        if [ $? -ne 0 ]; then
          echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "编译失败!!!" ;
          return 1;
        fi

        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "编译成功."
      fi

      if [ -d res-runtime ]; then
        cp -rn res-runtime/.  ./
      fi
    cd -
}

function vue_build(){

    cd $folder
      pwd

      install_package

      echo "﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹎﹎﹎"
      echo -e `date "+%Y-%m-%d %H:%M:%S"` "${env_packageTool} run "${buildScript}
      echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹉﹊﹊"

      ${env_packageTool} run ${buildScript}

      if [ $? -ne 0 ]; then
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "构建失败!!!" ;
        return 1;
      fi

      echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "构建成功"

      if [ -d res-runtime ]; then
        cp -rn res-runtime/.  dist/
      fi
    cd -

}



function python_build(){
    cd $folder
      pwd

      if [ -d res-runtime ]; then
        cp -rn res-runtime/.  ./
      fi
    cd -
}

function php_build(){
    cd $folder
      pwd

      if [ -d res-runtime ]; then
        cp -rn res-runtime/.  ./
      fi
    cd -
}

function post_build(){
    if [ -f $folder/post_build.sh ]; then
        echo "重要消息!编译后钩子: bash $folder/post_build.sh "
        source $folder/post_build.sh
    fi


    if [ -f ./post_build.sh ]; then
        echo "重要消息!编译后钩子: post_build.sh"
        source ./post_build.sh
    fi

    if [ -f ./sys-post-build.sh ]; then
        echo "重要消息!编译后钩子: sys-post-build.sh"
        source ./sys-post-build.sh
    fi
}



function check-mvn-build(){
    if [ "$language" != "Java" ]; then
      return
    fi

    echo "检测 spring-boot-maven-plugin 插件 layout"
    echo "cat $folder/pom.xml | grep '<artifactId>spring-boot-maven-plugin</artifactId>' | wc -l"
    txt=$(cat $folder/pom.xml | grep '<artifactId>spring-boot-maven-plugin</artifactId>' | wc -l)

    if [ $txt -ne 0 ]; then
        echo "cat $folder/pom.xml | grep '<layout>ZIP</layout>' | wc -l"
        txt=$(cat $folder/pom.xml | grep '<layout>ZIP</layout>' | wc -l)
        if [ $txt -eq 0 ]; then
            echo "!!!!!!!!!!!!!!!!!!!!!!!!"
            echo "$folder/pom.xml 中的 build.plugins.plugin 下 org.springframework.boot:spring-boot-maven-plugin.configuration.layout 必须为 ZIP!"
            echo "参考以下内容(使用了全角尖括号)："
            echo "＜plugin＞"
            echo "    ＜groupId＞org.springframework.boot＜/groupId＞"
            echo "    ＜artifactId＞spring-boot-maven-plugin＜/artifactId＞"
            echo "    ＜configuration＞"
            echo "        ＜layout＞ZIP＜/layout＞"
            echo "    ＜/configuration＞"
            echo "＜/plugin＞"
            echo "!!!!!!!!!!!!!!!!!!!!!!!!"
            return 12
        fi

        echo "检测通过! spring-boot-maven-plugin layout=ZIP!"
    else
        echo "!!!!!!!!!!!!!!!!!!!!!!!!"
        echo "$folder/pom.xml 必须存在 org.springframework.boot:spring-boot-maven-plugin !"
        echo "参考以下内容(使用了全角尖括号)："
        echo "＜plugin＞"
        echo "    ＜groupId＞org.springframework.boot＜/groupId＞"
        echo "    ＜artifactId＞spring-boot-maven-plugin＜/artifactId＞"
        echo "    ＜configuration＞"
        echo "        ＜layout＞ZIP＜/layout＞"
        echo "    ＜/configuration＞"
        echo "＜/plugin＞"
        echo "!!!!!!!!!!!!!!!!!!!!!!!!"
        return 13
    fi

    echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "获取mvn依赖，并去除空行，去重"
    echo "mvn dependency:tree -e -U -am  -P k8s -pl $folder | grep :compile | rev |  cut -d ' ' -f 1 | rev |  grep -v "^$""
    mvn dependency:tree -e -U -am  -P k8s -pl $folder | grep :compile | rev |  cut -d ' ' -f 1 | rev |  grep -v "^$"> .ops.mvn.txt

    if [ $? -ne 0 ]; then
        echo "mvn执行出错!"
        mvn dependency:tree -e -U -am  -P k8s -pl $folder
        return 11
    fi


    echo "检测 openfeign 组件"
    echo "cat .ops.mvn.txt | grep openfeign | wc -l "
    txt=$(cat .ops.mvn.txt | grep openfeign | wc -l)
    if [ $txt -ne 0 ]; then
        echo "存在 openfeign 组件,检测必须存在 spring-retry 组件"
        echo "cat .ops.mvn.txt | grep spring-retry  | wc -l"
        txt=$(cat .ops.mvn.txt | grep spring-retry  | wc -l)
        if [ $txt -eq 0 ]; then

            echo "!!!!!!!!!!!!!!!!!!!!!!!!"
            echo "项目存在 openfeign 包，要求必须引入 org.springframework.retry:spring-retry 包, 请添加后再部署!"
            echo "参考以下内容(使用了全角尖括号)：："
            echo "＜dependency＞"
            echo "    ＜groupId＞org.springframework.retry＜/groupId＞"
            echo "    ＜artifactId＞spring-retry＜/artifactId＞"
            echo "＜/dependency＞"
            echo "!!!!!!!!!!!!!!!!!!!!!!!!"
            return 14;
        fi


        echo "检测通过! 存在 openfeign,spring-retry"
    fi


    snapshot=$(cat .ops.mvn.txt | grep "SNAPSHOT" | rev |  cut -d ' ' -f 1 | rev | sort | uniq)
    line_count=$(echo "$snapshot" | awk 'END{print NR}')

    if [ $line_count -gt 0 ]; then
        echo "警告：发现 $line_count 个SNAPSHOT包！谨慎应用于生产环境！"
        echo "﹍﹎﹍﹎﹍﹎﹎﹎"
        echo "$snapshot"
        echo "﹊﹉﹊﹉﹊﹉﹊﹊"
    fi

    echo "cat .ops.mvn.txt | curl -X POST -o  curl-result.txt -s -w %{http_code} --max-time 6 --retry 3 -H'Content-type:text/plain' --data-binary @- $env_mpApiUrl/ops/cmd/mvn-dependency-check "
    code=$(cat .ops.mvn.txt | curl -X POST -o  curl-result.txt -s -w %{http_code} --max-time 6 --retry 3 -H"Content-type:text/plain" --data-binary @- $env_mpApiUrl/ops/cmd/mvn-dependency-check)

    if [ "$code" == "000" ]; then
        echo "网络错误，请重试！"
        return 3;
    elif [ "$code" != "200" ]; then
        echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "检查依赖接口错误!!! 返回: $code"
        show-file curl-result.txt 100
        return 16
    fi
}


function ms-deploy-env-yml(){

    folder="$1"
    $sudo chmod a+rw code -R

    echo "mkdir -p res/yml && mkdir -p res/lib && mkdir -p code/$folder/lib-runtime "
    mkdir -p res/yml && mkdir -p res/lib && mkdir -p code/$folder/lib-runtime


    resources=$(find code/$folder -type d -name resources | grep -v test | sort | head -1)

    if [ "$resources" != "" ]; then
        fc=$(ls res/yml/ -l|grep "^-"| wc -l)
        if [ $fc -gt 0 ]; then
            echo "mv -n res/yml/*  $resources/"
            mv -n res/yml/* $resources/
        fi
    else
        echo "找不到 code/$folder 文件夹下的 resources!"
    fi

    fc=$(ls res/lib/ -l|grep "^-"| wc -l)

    if [ $fc -gt 0 ]; then
        echo "mv -n res/lib/*  code/$folder/lib-runtime/"
        mv -n res/lib/*  code/$folder/lib-runtime/
    fi

    if [ -f "res/web-server.zip" ]; then
        echo "unzip -q -o res/web-server.zip -d code/$folder/web-server"
        unzip -q -o res/web-server.zip -d code/$folder/web-server
    fi


    if [ -f "res/res.zip" ]; then
        echo "unzip -q -o res/res.zip -d code/$folder/res-runtime"
        unzip -q -o res/res.zip -d code/$folder/res-runtime
    fi

}

function build(){
  set -eo pipefail

  export BUILD_DONE=false
  pre_build

  if [ "$BUILD_DONE" == "false" ]; then
    if [ -f $folder/build.sh ]; then
        echo "重要消息!项目存在自定义编译脚本: $folder/build.sh"
        bash $folder/build.sh
    else
        echo -e `date "+%Y-%m-%d %H:%M:%S"` "编译打包..."
        ${language}_build
    fi
  fi

  post_build
}
